package com.lang8.user.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lang8.user.dao.UserDao;
import com.lang8.user.po.UserInfo;
import com.lang8.util.CodeUtil;
import com.lang8.util.WebUtil;
import com.lang8.util.ioc.BeanManager;
import com.lang8.util.mail.MailUtil;

@WebServlet("/servlet/US")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserDao userDao = (UserDao)BeanManager.getBean(UserDao.class);
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action == null || action.trim().length() == 0) {
			return;
		}
		if (action.trim().equalsIgnoreCase("register")) {
			register(request, response);
			return;
		}
	}
	private void register(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String loginId = request.getParameter("loginId");
		String password = request.getParameter("password");
		String nickName = request.getParameter("nickName");
		String nativeLang = request.getParameter("nativeLang");
		String learningLang = request.getParameter("learningLang");
		UserInfo userInfo = new UserInfo();
		userInfo.setLoginId(loginId);
		userInfo.setPassword(CodeUtil.convertToMd5(password));
		userInfo.setNickName(nickName);
		userInfo.setNativeLang(nativeLang);
		userInfo.setLearningLang(learningLang);
		Date currentDate = new Date();
		userInfo.setCreateTime(currentDate);
		userInfo.setLastLoginTime(currentDate);
		userInfo.setLastModifyTime(currentDate);
		String ip = WebUtil.getIpAddr(request);
		userInfo.setCreateIp(ip);
		userInfo.setLastLoginIp(ip);
		userInfo.setLastModifyIp(ip);
		userDao.insertUser(userInfo);
		//send email
		try {
			String uuid = userDao.insertRegisterEmail(userInfo);
			sendEmail(userInfo, uuid);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		//http://lang-8.com/register/step3/2738239558242a503e7d4cd3f235c2ab
		response.sendRedirect(request.getContextPath() + "/jsp/user/registerstep2.jsp");
	}
	private void sendEmail(UserInfo userInfo, String uuid) {
		MailUtil mailUtil = new MailUtil();
		mailUtil.send();
	}
}
